import initDevice from './initDevice'
import { MODS, READ_IDCARD, READ_BCR, CLOSE_MOD, OPEN_MODULE, OPEN_STATE } from './code';
import { setRes } from './utils'
import { acceptAndReadTracks, getTrack3, closeIDCardStep } from './logic/idCardStep';
import { readBarcodeStep, closeBcrStep } from './logic/bcrStep';

let result;
let data;
let msg;
let retKeys;
let retCode;

/**
 * 将变量值重置，防止污染下次使用变量
 */
function resetVarible() {
  result = null;
  data = null;
  msg = null;
  retKeys = null;
  retCode = null;
}

/**
 * 处理返回数据，将模块事件统一化处理
 */
function handleRes(ret, callback, element, data) {
  retKeys = Object.keys(element)
  retCode = Object.values(element)[0]
  if (ret == retKeys) {
    switch (retCode === '00000') {
      case true:
        setRes(retCode, msg, data, true, callback.success)
        resetVarible()
        break;
      case false:
        setRes(retCode, msg, data, false, callback.fail)
        resetVarible()
        break;
    }
  }
}

export default class JsInterface {
  /**
   * 接口实例化方法，初始化模块 
   */
  constructor() { }

  /**
   * 初始化各模块
   */
  async SDKInterface(callback) {
    result = await initDevice(callback)
    let str = ''
    result.forEach((item) => {
      str = str + `@@${item.mod} ${item.ret}@@`
    })
    msg = str
    // 不清楚初始化模块需求，暂定为一定能打开
    OPEN_MODULE.forEach(element => {
      handleRes(OPEN_STATE.ConnectionOpened, callback, element, data)
    });
  }

  /**
   * 读取身份证信息
   */
  async getIDCard(callback) {
    const modName = MODS.IDCard
    result = await acceptAndReadTracks()
    msg = `${modName} ${result}`
    data = await getTrack3()
    READ_IDCARD.forEach(element => {
      handleRes(result, callback, element, data)
    });
  }

  /**
   * 关闭身份证读卡器
   */
  async closeIdCard(callback) {
    const modName = MODS.IDCard
    result = await closeIDCardStep()
    msg = `${modName} ${result}`

    CLOSE_MOD.forEach(element => {
      handleRes(result, callback, element, data)
    });
  }

  /**
   * 启动二维码扫描
   */
  async readBarcode(callback) {
    const modName = MODS.Barcode
    result = await readBarcodeStep()
    let ret = result.ret
    msg = `${modName} ${result.ret}`
    data = result.param[1]

    READ_BCR.forEach(element => {
      handleRes(ret, callback, element, data)
    });
  }

  /**
   * 关闭二维码扫描
   */
  async closeBcr(callback) {
    const modName = MODS.Barcode
    result = await closeBcrStep()
    msg = `${modName} ${result}`

    CLOSE_MOD.forEach(element => {
      handleRes(result, callback, element, data)
    });
  }
}
